package com.af.security.auth.login.lock;

import com.af.security.property.SecurityProperties;
import org.springframework.stereotype.Service;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author : zhenyun.su
 * @comment : 用户连续登录失败次数， 超过指定最大尝试值，则用户被锁定
 * 最大尝试值： szy.security.loginFailure.maxAttempt
 * @since : 2019/6/24
 */

@Service
public class LoginFailureCache {
    private Map<String, Integer> cache = new ConcurrentHashMap<>();
    private LockedUserHandler lockedUserHandler;
    private Integer maxAttempt = 8;

    public LoginFailureCache(LockedUserHandler lockedUserHandler, SecurityProperties securityProperties) {
        this.lockedUserHandler = lockedUserHandler;
        this.maxAttempt = securityProperties.getLoginFailureMaxAttempt();
    }

    public int getCacheValue(String key) {
        Integer count = cache.get(key);
        if (count != null) {
            return count;
        }
        return 0;
    }

    public void loginSucceeded(String key) {
        cache.remove(key);
    }

    public void loginFailed(String key) {
        Integer attempt = this.getCacheValue(key);
        cache.put(key, attempt + 1);
        if (isBlocked(key)){
            lockedUserHandler.userLocked(key, false);
            cache.remove(key);
        }
    }

    public Boolean isBlocked(String key) {
        return getCacheValue(key) >= maxAttempt;
    }
}
